package com.aispeech.jarpc.op.asrpp;

import com.aispeech.jarpc.TextBin;
import com.aispeech.jarpc.op.AbstractRequest;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OfflineRequest extends AbstractRequest {
    private final static String REQ_TMPL = "{\"op\":\"%s\",\"cfg\":\"%s\",\"start_param\":\"%s\",\"feed_param\":\"%s\"}";
    private final static ObjectMapper objectMapper = new ObjectMapper();

    private int sampleRate;
    private StartParam startParam;
    private List<Align> aligns;

    public OfflineRequest(int concurrency, int sampleRate, String wavPath) {
        this.startParam = new StartParam(concurrency, wavPath);

        this.sampleRate = 8000 == sampleRate ? sampleRate : 16000;

        aligns = new ArrayList<>();
    }

    public void add(int begin, int end) {
        aligns.add(new Align(begin, end));
    }

    public int size() {
        return aligns.size();
    }

    @Override
    public String OpType() {
        return "asrpp";
    }

    @Override
    public String toJson() throws IOException {
        String cfg = String.format("[RES]/cn/asrpp_%d.cfg", sampleRate);
        return String.format(REQ_TMPL, OpType(), cfg,
                objectMapper.writeValueAsString(startParam).replace("\"", "\\\""),
                objectMapper.writeValueAsString(aligns).replace("\"", "\\\""));
    }

    public TextBin toJsonBin() throws IOException {
        String json = toJson();
        return new TextBin(json, new byte[0]);
    }

    class StartParam {
        private int concurrency;
        private String wav_path;

        public StartParam(int concurrency, String wavPath) {
            this.concurrency = concurrency;
            this.wav_path = wavPath;
        }

        public String getWav_path() {
            return wav_path;
        }

        public void setWav_path(String wav_path) {
            this.wav_path = wav_path;
        }

        public int getConcurrency() {
            return concurrency;
        }

        public void setConcurrency(int concurrency) {
            this.concurrency = concurrency;
        }
    }


    class Align {
        private int begin;
        private int end;

        public Align(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        public int getBegin() {
            return begin;
        }

        public void setBegin(int begin) {
            this.begin = begin;
        }

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }
    }
}
